// 等待DOM加载完成
document.addEventListener('DOMContentLoaded', function() {
    // 移动端导航菜单切换
    const menuToggle = document.querySelector('.menu-toggle');
    const mainNav = document.querySelector('.main-nav');
    
    if (menuToggle) {
        menuToggle.addEventListener('click', function() {
            mainNav.classList.toggle('show');
            // 切换汉堡菜单图标
            const bars = menuToggle.querySelectorAll('span');
            bars[0].classList.toggle('rotate-45');
            bars[1].classList.toggle('opacity-0');
            bars[2].classList.toggle('rotate-neg-45');
        });
    }
    
    // 轮播图功能
    const carousel = document.querySelector('.carousel');
    if (carousel) {
        const carouselContainer = carousel.querySelector('.carousel-container');
        const slides = carousel.querySelectorAll('.carousel-slide');
        const prevBtn = carousel.querySelector('.carousel-prev');
        const nextBtn = carousel.querySelector('.carousel-next');
        const indicators = carousel.querySelectorAll('.carousel-indicator');
        
        let currentSlide = 0;
        const slideCount = slides.length;
        
        // 更新轮播图位置
        function updateCarousel() {
            carouselContainer.style.transform = `translateX(-${currentSlide * 25}%)`;
            
            // 更新指示器状态
            indicators.forEach((indicator, index) => {
                if (index === currentSlide) {
                    indicator.classList.add('active');
                } else {
                    indicator.classList.remove('active');
                }
            });
        }
        
        // 下一张幻灯片
        function nextSlide() {
            currentSlide = (currentSlide + 1) % slideCount;
            updateCarousel();
        }
        
        // 上一张幻灯片
        function prevSlide() {
            currentSlide = (currentSlide - 1 + slideCount) % slideCount;
            updateCarousel();
        }
        
        // 绑定按钮事件
        if (nextBtn) {
            nextBtn.addEventListener('click', nextSlide);
        }
        
        if (prevBtn) {
            prevBtn.addEventListener('click', prevSlide);
        }
        
        // 绑定指示器事件
        indicators.forEach((indicator, index) => {
            indicator.addEventListener('click', () => {
                currentSlide = index;
                updateCarousel();
            });
        });
        
        // 自动轮播
        let autoPlay = setInterval(nextSlide, 5000);
        
        // 鼠标悬停时暂停自动轮播
        carousel.addEventListener('mouseenter', () => {
            clearInterval(autoPlay);
        });
        
        // 鼠标离开时恢复自动轮播
        carousel.addEventListener('mouseleave', () => {
            autoPlay = setInterval(nextSlide, 5000);
        });
        
        // 初始化轮播图
        updateCarousel();
    }
    
    // 表单验证
    const forms = document.querySelectorAll('form[data-validate]');
    
    forms.forEach(form => {
        form.addEventListener('submit', function(e) {
            let isValid = true;
            
            // 获取所有必填字段
            const requiredFields = form.querySelectorAll('[required]');
            
            // 验证每个必填字段
            requiredFields.forEach(field => {
                // 移除之前的错误消息
                const existingError = field.parentNode.querySelector('.error-message');
                if (existingError) {
                    existingError.remove();
                }
                
                field.classList.remove('input-error');
                
                // 检查是否为空
                if (!field.value.trim()) {
                    isValid = false;
                    field.classList.add('input-error');
                    
                    // 创建错误消息
                    const errorMsg = document.createElement('div');
                    errorMsg.className = 'error-message';
                    errorMsg.textContent = '此字段不能为空';
                    field.parentNode.appendChild(errorMsg);
                }
                
                // 验证电子邮件格式
                if (field.type === 'email' && field.value.trim()) {
                    const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                    if (!emailPattern.test(field.value)) {
                        isValid = false;
                        field.classList.add('input-error');
                        
                        // 创建错误消息
                        const errorMsg = document.createElement('div');
                        errorMsg.className = 'error-message';
                        errorMsg.textContent = '请输入有效的电子邮箱地址';
                        field.parentNode.appendChild(errorMsg);
                    }
                }
                
                // 验证电话号码
                if (field.type === 'tel' && field.value.trim()) {
                    const telPattern = /^1[3-9]\d{9}$/;
                    if (!telPattern.test(field.value)) {
                        isValid = false;
                        field.classList.add('input-error');
                        
                        // 创建错误消息
                        const errorMsg = document.createElement('div');
                        errorMsg.className = 'error-message';
                        errorMsg.textContent = '请输入有效的手机号码';
                        field.parentNode.appendChild(errorMsg);
                    }
                }
            });
            
            // 如果表单无效，阻止提交
            if (!isValid) {
                e.preventDefault();
            } else {
                // 表单验证通过，可以在此处添加提交成功的处理逻辑
                // 例如显示成功消息或重定向
                console.log('表单提交成功');
            }
        });
    });
    
    // 页面滚动动画效果
    window.addEventListener('scroll', function() {
        const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
        
        // 淡入元素
        const fadeInElements = document.querySelectorAll('.fade-in');
        fadeInElements.forEach(element => {
            const elementTop = element.getBoundingClientRect().top + scrollTop;
            if (scrollTop + window.innerHeight > elementTop + 100) {
                element.classList.add('visible');
            }
        });
        
        // 从左侧滑入元素
        const slideInLeftElements = document.querySelectorAll('.slide-in-left');
        slideInLeftElements.forEach(element => {
            const elementTop = element.getBoundingClientRect().top + scrollTop;
            if (scrollTop + window.innerHeight > elementTop + 100) {
                element.classList.add('visible');
            }
        });
        
        // 从右侧滑入元素
        const slideInRightElements = document.querySelectorAll('.slide-in-right');
        slideInRightElements.forEach(element => {
            const elementTop = element.getBoundingClientRect().top + scrollTop;
            if (scrollTop + window.innerHeight > elementTop + 100) {
                element.classList.add('visible');
            }
        });
    });
    
    // 平滑滚动到锚点
    const smoothScrollLinks = document.querySelectorAll('a[href^="#"]:not([href="#"])');
    
    smoothScrollLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            
            const targetId = this.getAttribute('href');
            const targetElement = document.querySelector(targetId);
            
            if (targetElement) {
                window.scrollTo({
                    top: targetElement.offsetTop - 120, // 考虑固定导航栏的高度
                    behavior: 'smooth'
                });
                
                // 如果在移动设备上展开了菜单，点击链接后关闭菜单
                if (window.innerWidth < 768 && mainNav.classList.contains('show')) {
                    mainNav.classList.remove('show');
                }
            }
        });
    });
    
    // 登录表单处理
    const loginForm = document.getElementById('login-form');
    if (loginForm) {
        loginForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const username = loginForm.querySelector('#username').value;
            const password = loginForm.querySelector('#password').value;
            
            // 在实际项目中，这里应该发送请求到服务器验证登录信息
            // 这里只做简单的前端验证示例
            if (username && password) {
                console.log('登录成功');
                // 登录成功后，重定向到首页或其他页面
                window.location.href = 'index.html';
            } else {
                console.log('登录失败');
                alert('用户名或密码不能为空');
            }
        });
    }
});
